package com.softeware.control;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import com.softeware.pojo.Message;
import com.softeware.service.MessageService;

import java.io.IOException;
import java.util.List;

@WebServlet("/MessageServlet")
public class MessageServlet extends HttpServlet {
    private MessageService messageService = new MessageService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Message> messages = messageService.getMessages(request.getServletContext());
        request.setAttribute("messages",messages);
        request.getRequestDispatcher("/message.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String author = (String) request.getSession().getAttribute("username");
        String subject = request.getParameter("subject");
        String content = request.getParameter("content");

        Message message = new Message();
        message.setAuthor(author);
        message.setSubject(subject);
        message.setContent(content);

        messageService.addMessage(message, request.getServletContext());
        request.setAttribute("messages",messageService.getMessages(request.getServletContext()));
//        response.sendRedirect("message.jsp");
        request.getRequestDispatcher("/message.jsp").forward(request,response);
    }
}